package com.yswy.backstage.serviceApi.impl;

import com.alibaba.nacos.common.util.Md5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yswy.backstage.dto.api.AppEventCallback;
import com.yswy.backstage.dto.api.TgCallBackIdReids;
import com.yswy.backstage.dto.api.UserDeviceInfo;
import com.yswy.backstage.service.TgEventEnumsService;
import com.yswy.backstage.service.TgEventService;
import com.yswy.backstage.serviceApi.ApiTgCallBackKsIdService;
import com.yswy.backstage.serviceApi.ApiTgCallBackLoglService;
import com.yswy.backstage.serviceApi.ApiTgChannelService;
import com.yswy.backstage.utils.BackStringUtils;
import com.yswy.common.enums.TfPlatformEnums;
import com.yswy.common.runnableUtil.Pooled;
import com.yswy.common.utils.HttpUtil;
import com.yswy.common.utils.StringUtils;
import com.yswy.common.utils.redis.RedisConstants;
import com.yswy.common.utils.redis.RedisUtil;
import com.yswy.domain.entity.tf.*;
import com.yswy.domain.mapper.tf.TgCallBackKsIdMapper;
import com.yswy.domain.vo.dto.TgDeviceKs;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class ApiTgCallBackKsIdServiceImpl extends ServiceImpl<TgCallBackKsIdMapper, TgCallBackKsId>
        implements ApiTgCallBackKsIdService {
    @Autowired
    private  RedisUtil redisUtil ;
    @Autowired
    private  ApiTgChannelService apiTgChannelService ;
    @Autowired
    private  ApiTgCallBackLoglService apiTgCallBackLoglService ;
    @Autowired
    private  TgEventService tgEventService ;
    @Override
    @Pooled(executor = "tgCallBackIdInp", poolOverAct = Pooled.PoolOverAct.NEW_THREAD)
    public void addTgCallBackKsId(String channel ,String packChannel ,Long projectId , TgDeviceKs tgDeviceKs) {
        if (StringUtils.isEmpty(tgDeviceKs.getCALLBACK()))return;
        if (StringUtils.isEmpty(channel))return;

        TgCallBackKsId tgCallBackKsId = new TgCallBackKsId(channel,packChannel,projectId , tgDeviceKs);
        String isCacheTgBack = RedisConstants.isCacheTgBack_clzt+tgCallBackKsId.getCallbackparamCrc();
        if (redisUtil.hasKey(isCacheTgBack)){
            return;
        }
        Integer count = count(new LambdaQueryWrapper<TgCallBackKsId>()
                .eq(TgCallBackKsId::getCallbackparamCrc ,tgCallBackKsId.getCallbackparamCrc()));
        if (count<=0){
            save(tgCallBackKsId);
            redisUtil.setForObjectTimeCustom(isCacheTgBack, tgCallBackKsId, 5, TimeUnit.MINUTES);
            TgEvent tgEvent = tgEventService.getTgEventByChannel(channel);
            if (tgEvent == null){
                log.info("快手渠道"+channel+"未配置参数");
                return;
            }
            List<TgEventChild> tgEventChilds = tgEvent.getTgEventChildrens();
            if (tgEventChilds.size()<=0){
                log.info("快手渠道"+channel+"未配置参数");
                return;
            }

            for (TgEventChild tc:tgEventChilds) {
                String oaidCache = null;
                String ipCache = null;
                if (StringUtils.isNotEmpty(tgCallBackKsId.getOaid())){
                    oaidCache = BackStringUtils.getTgCallbackKey(RedisConstants.cacheTgBack_oaid_clzt
                            ,tgCallBackKsId.getOaid() ,packChannel , projectId ,  tc.getTriggerNode());
                }
                if (StringUtils.isNotEmpty(tgCallBackKsId.getChannelIp())){
                    ipCache =  BackStringUtils.getTgCallbackKey(RedisConstants.cacheTgBack_ip_clzt
                            ,tgCallBackKsId.getChannelIp() ,packChannel , projectId ,  tc.getTriggerNode());
                }

                if (StringUtils.isNotEmpty(oaidCache)){
                    redisUtil.setForObjectTimeCustom(oaidCache, tgCallBackKsId, tc.getCacheTime(), TimeUnit.DAYS);
                }
                if (StringUtils.isNotEmpty(ipCache)){
                    redisUtil.setForObjectTimeCustom(ipCache, tgCallBackKsId, tc.getCacheTime(), TimeUnit.DAYS);
                }
            }

        }
    }


    @Override
    public TgCallBackLog callBack(AppEventCallback appEventCallback , TgCallBackIdReids tgCallBackIdReids , TgEventEnums tgEventEnums) {
        TgCallBackKsId tgCallBackKsId = tgCallBackIdReids.getTgCallBackKsId() ;
        String oaidMd5 = tgCallBackIdReids.getOaidCache();
        String modelIpMd5 =tgCallBackIdReids.getIpCache();
        Integer price = appEventCallback.getPrice();
        UserDeviceInfo userDeviceInfo = appEventCallback.getUserDeviceInfo();
        Boolean isDeduction = false ;
        if (tgEventEnums.getIsBuckle() == 1){
            isDeduction = apiTgChannelService.isDeduction(tgCallBackKsId.getChannel() , price);
        }
        //回传登录Key  active
        String eventKey =tgEventEnums.getEventKey();
        TgCallBackLog tgCallBackLog = new TgCallBackLog();
        tgCallBackLog.setTfPlatform(TfPlatformEnums.JLYQ.toString());
        tgCallBackLog.setUserId(userDeviceInfo.getUserId());
        tgCallBackLog.setBackJlId(tgCallBackKsId.getId());
        tgCallBackLog.setTgEventEnumsId(tgEventEnums.getId());
        tgCallBackLog.setIsDeduction(isDeduction);
        //回传
        if (!isDeduction){
            String body = callBack(tgCallBackKsId ,eventKey );
            tgCallBackLog.setCallbackBody(body);
        }

        redisUtil.delete(oaidMd5);
        redisUtil.delete(modelIpMd5);
        apiTgCallBackLoglService.save(tgCallBackLog);
        return tgCallBackLog;

    }



    public static String callBack(TgCallBackKsId tgCallBackKsId , String eventEype){
        String url = tgCallBackKsId.getCallback()+"&event_type="+eventEype+"&event_time="+new Date().getTime();
        String body = HttpUtil.doGet(url);
        log.info("快手联调 , 响应："+body + " callback: "+tgCallBackKsId.getCallback()+ " eventEype: "+eventEype);
        return body;
    }

}

